<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<title></title>
		<link href="../css/mui.min.css" rel="stylesheet" />
		<link rel="stylesheet" type="text/css" href="../css/common.css" />
		<link rel="stylesheet" type="text/css" href="../css/chat-msg.css" />
		<style type="text/css">
			html,
			body {
				height: 100%;
				margin: 0px;
				padding: 0px;
				overflow: hidden;
				-webkit-touch-callout: none;
				-webkit-user-select: none;
			}

			.mui-content {
				height: 100%;
				padding: 44px 0px 50px 0px;
				overflow: auto;
			}
			
			#msg-list {
				height: 100%;
				overflow: auto;
				-webkit-overflow-scrolling: touch;
			}
			
			footer {
				position: fixed;
				width: 100%;
				height: 50px;
				min-height: 50px;
				border-top: solid 1px #bbb;
				left: 0px;
				bottom: 0px;
				overflow: hidden;
				padding-left: 10px;
				padding-right: 50px;
				background-color: #fafafa;
			}
			
			.footer-left {
				position: absolute;
				width: 50px;
				height: 50px;
				left: 0px;
				bottom: 0px;
				text-align: center;
				vertical-align: middle;
				line-height: 100%;
				padding: 12px 4px;
			}
			
			.footer-left input[type="file"] {
				position: absolute;
				left: 0px;
				top: 0px;
				width: 100%;
				height: 100%;
				opacity: 0;
				cursor: pointer;
				z-index: 0;
			}
			
			.footer-right {
				position: absolute;
				width: 50px;
				height: 50px;
				right: 0px;
				bottom: 0px;
				text-align: center;
				vertical-align: middle;
				line-height: 100%;
				padding: 12px 5px;
				display: inline-block;
			}
			
			.footer-center {
				height: 100%;
				padding: 5px 0px;
			}
			
			.footer-center [class*=input] {
				width: 100%;
				height: 100%;
				border-radius: 5px;
			}
			
			.footer-center .input-text {
				background: #fff;
				border: solid 1px #ddd;
				padding: 10px !important;
				font-size: 16px !important;
				line-height: 18px !important;
				font-family: verdana !important;
				overflow: hidden;
			}
			
			.footer-center .input-sound {
				background-color: #eee;
			}
			
			/*footer .mui-icon {
				color: #000;
			}
			
			footer .mui-icon:active {
				color: #F6047F !important;
			}*/
			
			.footer-right span {
				color: #FEB406;
				line-height: 30px;
			}
		</style>
	</head>

	<body>
		<header class="mui-bar mui-bar-nav bar-inverse">
			<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
			<a class="mui-icon mui-pull-right iconfont">&#xe657;</a>
			<h1 class="mui-title" id="stageName"></h1>
		</header>
		<div class="mui-content">
			<div id="msg-list"></div>
		</div>
		<footer>
			<!--<div class="footer-left">
				<i id='msg-choose-img' class="mui-icon mui-icon-image"></i>
			</div>-->
			<div class="footer-center">
				<textarea id='msg-text' type="text" class='input-text' autofocus></textarea>
			</div>
			<div class="footer-right">
				<span id='msg-send-text'>发送</span>
			</div>
		</footer>

		<script src="../js/mui.min.js"></script>
		<!--sdk-->
		<script src="../sdk/strophe.js"></script>
		<script src="../sdk/easemob.im-1.1.js"></script>
		<script src="../sdk/easemob.im-1.1.shim.js"></script>
		<!--兼容老版本sdk需引入此文件-->
		<!--config-->
		<script src="../js/easemob.im.config.js" type="text/javascript" charset="utf-8"></script>
		<script src="../js/chatMsg.js"></script>
		<script src="../js/common.js" type="text/javascript" charset="utf-8"></script>
		<script src="../js/user.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript" charset="UTF-8">
			var self = null,
				releaseId = null,
				releasePic = null,
				myId = null,
				myName = null,
				msgInit = null;
			var firstSend = false; // 第一次发送时发送通知消息
			mui.plusReady(function() {
				self = plus.webview.currentWebview();
				releaseId = self.releaseId;
				releasePic = self.pic;
				var chatName = releaseId;
				myId = User.getMyID();
				myName = User.getMyNickName();
				var linkURL = baseURL + 'message/sendNotify/' + myId + '/' + releaseId + '/' + myName + '.json';
				document.getElementById("stageName").innerText = self.sName;
				// 消息初始化
				msgInit = {
					el: '#msg-list', //消息容器
					senderAvatar: Common.artistPic + myId + User.getMyPic() + '?' + Math.random(), //发送者头像 (我的头像)
					receiverAvatar: Common.artistPic + releaseId + releasePic + '?' + Math.random(), //接收者头像 (对方头像)
				}

				// 加好友、发送推送消息
				Common.ajax({
					url : linkURL
				}, function(data) {
					console.log(JSON.stringify(data));
					if(data.code != 1) {
						mui.toast('连接失败，' + data.msg);
					}
				}, function(xhr) {
					mui.toast('网络异常，请稍后再试');
					console.error('failed - ' + xhr.status + ' : ' + xhr.statusText);
				})
				
				// UI控件对象
				var ui = {
					content: mui('.mui-content' [0]),
					msgList: mui('#msg-list')[0],
					footer: mui('footer')[0],
//					msgChooseImg: mui("#msg-choose-img")[0],
					msgInputText: mui('#msg-text')[0],
					msgSendText: mui('#msg-send-text')[0]
				}

				// mui初始化
				mui.init({
					gestureConfig: {
						tap: true, //默认为true
						doubletap: true, //默认为false
						longtap: true, //默认为false
						swipe: true, //默认为true
						drag: true, //默认为true
						hold: true, //默认为false，不监听
						release: true //默认为false，不监听
					}
				});

				console.log('from ' + myId);
				console.log('to   ' + chatName);
				
				var conn = new Easemob.im.Connection();

				// 初始化连接
				conn.init({
					onOpened: function() {
						mui.toast("连接成功");
						conn.setPresence();
					},
					onClosed: function(message) {
						mui.toast("连接关闭");
						console.error('连接出错，准备重新连接');
						conn.open({
							user: myId,
							pwd: myId,
							appKey: Easemob.im.config.appkey
						});
					},
					// 收到文本消息时的回调函数
					onTextMessage: function(message) {
						handleTextMessage(message.data);
					},
					// 收到图片消息时的回调函数
					onPictureMessage: function(message) {
						handlePictureMessage(message);
					},
					onError: function(message) {
						mui.toast('错误 ' + JSON.stringify(message));
					},
					// 本机网络连接成功
					onOnline: function() {
						mui.toast('本机网络连接成功');
					},
					// 本机网络掉线
					onOffline: function() {
						mui.toast('本机网络掉线');
					}
				})
				
				/*document.addEventListener('getMessage', function() {
					var message = event.detail.msg;
					console.log(JSON.stringify(message));
					var from = message.from; //消息的发送者
					var msg = message.data; //文本消息体	
					console.log('收到消息' + from + msg);
					if(from != releaseId) {
						mui.toast('他人消息');
					} else {
						// 收到文本消息在页面展示
						handleTextMessage(msg);
					}
				})*/
				
				// 打开连接
				conn.open({
					user: myId,
					pwd: myId,
					appKey: Easemob.im.config.appkey
				});

				// 发送文本消息
				ui.msgSendText.addEventListener('tap', function() {
					sendText();
				})

				// 发送图片
				/*ui.msgChooseImg.addEventListener('tap', function() {
					sendImg();
				})*/

				// 解决长按“发送”按钮，导致键盘关闭的问题；
				ui.msgSendText.addEventListener('touchstart', function(event) {
					msgInputTextFocus();
					event.preventDefault();
				});
				ui.msgSendText.addEventListener('touchmove', function(event) {
					msgInputTextFocus();
					event.preventDefault();
				});

				// 输入框监听事件
				ui.msgInputText.addEventListener('input', function(event) {
					msgInputTextFocus();
					ui.footer.style.height = this.scrollHeight + 'px';
				});

				// 调整窗口
				window.addEventListener('resize', function() {
					msgScrollTop();
				}, false);

				// 发送文本
				var sendText = function() {
					// 将换行和空格替换成安全的格式
					var msg = ui.msgInputText.value.replace(/\n/gm, '<br/>').replace(/\s/gm, '&nbsp;');
					// 获得输入框键盘焦点
					msgInputTextFocus();
					if(msg) {
						msgShow('sender', 'text', msg);
						// 发送文本消息到环信服务器
						var sendMsg = {
							to: chatName, //用户登录名，SDK根据AppKey和domain组织jid，如easemob-demo#chatdemoui_**TEST**@easemob.com，中"to:TEST",下同
							msg: msg, //文本消息
							type: "chat"/*,
							ext: { sender: self.sName } //用户自扩展的消息内容（群聊用法相同）*/
						};
						conn.sendTextMessage(sendMsg);
						console.log('发送消息 ' + JSON.stringify(sendMsg))
						// 清空文本框
						ui.msgInputText.value = '';
						// 恢复输入框高度(因为我们这里是50px)
						ui.footer.style.height = '50px';
						// 保持输入状态
						mui.trigger(ui.msgInputText, 'input', null);
						// 这一句让内容滚动起来
						msgScrollTop();
						var url = baseURL + 'message/send/' + myId + '/' + releaseId + '/' + myName + '.json';
						console.log(url);
						Common.ajax({
							url : url,
							type : 'POST',
							data : 'msg=' + msg
						}, function(data) {
							console.log(JSON.stringify(data));
							if(data.code != 1) {
								mui.toast('发送失败，请稍后重试');
							}
						}, function(xhr) {
							mui.toast('网络异常，请稍后再试');
							console.error('failed - ' + xhr.status + ' : ' + xhr.statusText);
						})
					} else {
						return;
					}
				}

				/**
				 * 接受文本消息的回调函数
				 * @param {Object} message
				 */
				var handleTextMessage = function(message) {
					console.log(JSON.stringify(message));
					msgShow('receiver', 'text', message);
					msgScrollTop();
				}

				/**
				 * 接受图片消息的回调函数
				 */
//				var handlePictureMessage = function(message) {
//					var maxWidth = 200;
//					var filename = message.filename; //文件名称，带文件扩展名
//					var from = message.from; //文件的发送者
//					var options = message;
//					// 图片消息下载成功后的处理逻辑
//					options.onFileDownloadComplete = function(response, xhr) {
//						var objectURL = Easemob.im.Helper.parseDownloadResponse.call(this, response);
//						img = document.createElement("img");
//						img.onload = function(e) {
//							img.onload = null;
//							window.URL.revokeObjectURL(img.src);
//						};
//						img.onerror = function() {
//							img.onerror = null;
//							if(typeof FileReader == 'undefined') {
//								img.alter = "当前浏览器不支持blob方式";
//								return;
//							}
//							img.onerror = function() {
//								img.alter = "当前浏览器不支持blob方式";
//							};
//							var reader = new FileReader();
//							reader.onload = function(event) {
//								img.src = this.result;
//							};
//							reader.readAsDataURL(response);
//						}
//						img.src = objectURL;
//						var pic_real_width = options.width;
//
//						if(!pic_real_width || pic_real_width == 0) {
//							pic_real_width = this.width;
//							if(pic_real_width > maxWidth) {
//								img.width = maxWidth;
//							} else {
//								img.width = pic_real_width;
//							}
//						} else {
//							if(pic_real_width > maxWidth) {
//								img.width = maxWidth;
//							} else {
//								img.width = pic_real_width;
//							}
//						}
//
//						// 展示接受的图片
//						msgShow('receiver', 'img', objectURL);
//						// 这一句让内容滚动起来
//						msgScrollTop();
//					};
//					options.onFileDownloadError = function(e) {
//						//下载失败时只重新下载一次
//						if(redownLoadFileNum < 1) {
//							redownLoadFileNum++;
//							options.accessToken = options_c;
//							Easemob.im.Helper.download(options);
//
//						} else {
//							mui.alert(e.msg + ",下载图片" + filename + "失败");
//							redownLoadFileNum = 0;
//						}
//					};
//					Easemob.im.Helper.download(options);
//				};

				// 消息滚动
				var msgScrollTop = function() {
					ui.msgList.scrollTop = ui.msgList.scrollHeight + ui.msgList.offsetHeight;
				}

				// 获得输入框键盘焦点
				var msgInputTextFocus = function() {
					ui.msgInputText.focus();
					setTimeout(function() {
						ui.msgInputText.focus();
					}, 150);
				}

				// 强制弹出软键盘
//				var showKeyboard = function() {
//					if(mui.os.ios) {
//						var webView = plus.webview.currentWebview().nativeInstanceObject();
//						webView.plusCallMethod({
//							"setKeyboardDisplayRequiresUserAction": false
//						});
//					} else if(mui.os.android) {
//						var Context = plus.android.importClass("android.content.Context");
//						var InputMethodManager = plus.android.importClass("android.view.inputmethod.InputMethodManager");
//						var main = plus.android.runtimeMainActivity();
//						var imm = main.getSystemService(Context.INPUT_METHOD_SERVICE);
//						imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
//					}
//				};
			})
			
			mui('header').on('tap', '.mui-pull-right', function() {
				Common.openWindow('chat-log.html', {
					sender : myId,
					receiver : releaseId,
					pic : releasePic
				})
			})
		</script>
	</body>

</html>